package zwz.importTask.utils;

import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.BooleanUtils;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Sheet;


public class ExportCellWriteHandler implements CellWriteHandler {

    /**
     * 最后一列的索引 用于设置错误信息那一列的字体颜色
     */
    private Integer lastColumnIndex;

    public ExportCellWriteHandler(Integer lastColumnIndex) {
        this.lastColumnIndex = lastColumnIndex;
    }

    @Override
    public void afterCellDispose(CellWriteHandlerContext context) {
        Sheet sheet = context.getWriteSheetHolder().getSheet();
        // 设置列宽
        sheet.setColumnWidth(context.getCell().getColumnIndex(), 10 * 256);
        context.getCell().getRow().setHeight((short) (15 * 20));
        WriteFont writeFont;
        if (BooleanUtils.isTrue(context.getHead())) {
            // 设置表头样式
            WriteCellData<?> cellData = context.getFirstCellData();
            WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
            writeFont = new WriteFont();
            writeFont.setFontName("微软雅黑");
            writeFont.setBold(true);
            writeFont.setFontHeightInPoints(Short.valueOf("11"));

            writeCellStyle.setWriteFont(writeFont);
            writeCellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
            writeCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        } else {
            // 设置表格内容样式
            WriteCellData<?> cellData = context.getFirstCellData();
            WriteCellStyle writeCellStyle = cellData.getOrCreateStyle();
            writeFont = new WriteFont();
            if (context.getColumnIndex().equals(lastColumnIndex)) {
                writeFont.setColor(Font.COLOR_RED);
            }
            writeFont.setFontName("宋体");
            writeFont.setFontHeightInPoints(Short.valueOf("10"));
            writeCellStyle.setWriteFont(writeFont);
        }
    }
}